import React, { Component, PropTypes } from 'react'
import { Form, Input, Button, Select, message, Icon, Row, Col, Spin } from 'antd'
import Style from '../Index.less'
import { fetchPost, getCaptcha } from '../../../utils/request'
import { history } from '../../../utils/config'
import Title from '../../common/components/Title'

const FormItem = Form.Item
const Option = Select.Option

/**
 * 安全设置
 */
class Index extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      loading: false,
      method: 'password',
      msgText: 'Send OTP',
      countFlag: true,
      count: 60,
      buttonHidden: false,
      account: {},
    }
  }

  componentDidMount () {
    this.getData()
  }

  getData () {
    this.setState({
      loading: true
    })
    fetchPost('/admin/security/info/get', {}).then(json => {
      if (json.code == 0) {
        let account = json.data
        this.setState({
          account: account,
          loading: false
        })
      } else {
        this.setState({
          account: null,
          loading: false
        })
        message.error(json.msg)
      }
    })
  }

  sendVerifyCode (e) {
    e.preventDefault()
    let account = this.state.account.account
    if (!this.state.countFlag) {
      return false
    }
    if (!account) {
      message.error('Please select your account')
      return false
    }

    this.setState({
      buttonHidden: true
    })

    getCaptcha(`/admin/${account}/sendVerifyCode`).then(res => {
      //   debugger;
      if (res.code == 0) {
        console.log(res, 'res')
        this.setState({
          countFlag: false,
          buttonHidden: false
        })
        this.timer = setInterval(() => {
          if (this.state.count <= 0) {
            clearInterval(this.timer)
            this.state.countFlag = true
            this.state.count = 60
            this.setState({
              // time: 60,
              msgText: 'Send OTP',
              countFlag: true
              // countFlag: true
            })
          } else {
            this.state.count--
            this.setState({
              msgText: `${this.state.count} s`
            })
          }
        }, 1000)
      }

    })
  }

  handleSubmit () {
    this.props.form.validateFields((errors, values) => {
      if (!errors) {
        let account = this.state.account.account
        const { password, newPassword, confirmPassword, verifyCode, verificationMethod } = values
        if (newPassword != confirmPassword) {
          message.error('Two input password must be consistent2222')
          return
        }
        fetchPost('/admin/password/update', {
          account,
          password,
          newPassword,
          verifyCode,
          verificationMethod
        }).then(json => {
          if (json.code === 0) {
            this.props.form.resetFields()
            this.timer && clearTimeout(this.timer)
            this.setState({
              method: 'otp',
              msgText: 'Send OTP',
              countFlag: true,
              count: 60,
              account: {},
            }, () => {
              this.getData()
            })
            message.info(json.msg)

          } else {
            message.error(json.msg)
          }
        })
      }
    })
  }

  handleReset () {
    this.props.form.resetFields()
  }

  render () {
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    }
    const { getFieldDecorator } = this.props.form
    return (
      <div>
        <Title title='Security Settings'/>
        <Spin spinning={this.state.loading}>
          <div className={Style.editAdminWrapper}>
            <Form horizontal>
              <FormItem
                {...formItemLayout}
                label='Login account'
              >
                {getFieldDecorator('account', {
                  initialValue: this.state.account.account || '',
                })(
                  <div>{this.state.account.account || ''}</div>
                )}
              </FormItem>

              <FormItem
                {...formItemLayout}
                label='Name'
              >
                {getFieldDecorator('name', {
                  initialValue: this.state.account.name || '',
                })(
                  <div>{this.state.account.name || ''}</div>
                )}
              </FormItem>

              <FormItem
                {...formItemLayout}
                label='Bound phone'
              >
                {getFieldDecorator('mobile', {
                  initialValue: this.state.account.mobile || '',
                })(
                  <div>{this.state.account.mobile || ''}</div>
                )}
              </FormItem>

              <FormItem
                {...formItemLayout}
                label='Authentication mode'
              >
                {getFieldDecorator('verificationMethod', {
                  initialValue: 'password',
                  rules: [
                    { required: true, message: 'Choose method' },
                  ],
                })(
                  <Select placeholder='Please' onChange={(e) => {
                    this.setState({
                      method: e
                    })
                  }}>
                    <Option key='otp'>Otp</Option>
                    <Option key='password'>Password</Option>
                  </Select>,
                )}
              </FormItem>

              {this.state.method === 'otp' ?
                <FormItem
                  {...formItemLayout}
                  label='Otp'
                  hasFeedback
                >
                  <Row gutter={8}>
                    <Col span={12}>
                      {getFieldDecorator('verifyCode', {
                        rules: [{ required: true, message: 'Enter OTP' }],
                      })(
                        <Input size="large" placeholder="Enter OTP"/>
                      )}
                    </Col>
                    <Col span={12}>
                      <Button size="large" disabled={this.state.buttonHidden}
                              onClick={(e) => this.sendVerifyCode(e)}>{this.state.msgText}</Button>
                    </Col>
                  </Row>
                </FormItem>
                :
                <FormItem
                  {...formItemLayout}
                  label='Original password'
                  hasFeedback
                >
                  {getFieldDecorator('password', {
                    rules: [
                      { required: true, message: 'Enter password' },
                      {
                        pattern: '^[0-9a-zA-Z_]{1,}$',
                        message: 'Must been digits and letters',
                      },
                    ],
                  })(
                    <Input/>,
                  )}
                </FormItem>
              }

              <FormItem
                {...formItemLayout}
                label='New password'
                hasFeedback
              >
                {getFieldDecorator('newPassword', {
                  initialValue: '',
                  rules: [
                    { required: true, message: 'please enter' },
                    {
                      pattern: '^[0-9a-zA-Z_]{1,}$',
                      message: 'Must been digits and letters',
                    },
                    {
                      pattern: '^[0-9a-zA-Z_]{6,}$',
                      message: 'At least six digits in length',
                    },
                    {
                      pattern: '^.{1,16}$',
                      message: 'Password length cannot exceed 16 characters',
                    }
                  ],
                })(
                  <Input/>,
                )}
              </FormItem>

              <FormItem
                {...formItemLayout}
                label='Confirm Password'
                hasFeedback
              >
                {getFieldDecorator('confirmPassword', {
                  initialValue: '',
                  rules: [
                    { required: true, message: 'please enter' },
                    {
                      validator: (rule, value, callback) => {
                        let newPassword = this.props.form.getFieldValue('newPassword')
                        if (!value || value === '' || value != newPassword) {
                          callback('Two input password must be consistent')
                        } else {
                          callback()
                        }
                      }
                    }
                  ],
                })(
                  <Input/>,
                )}
              </FormItem>

              <FormItem wrapperCol={{ span: 12, offset: 6 }}>
                <Button type='primary' onClick={() => this.handleSubmit()}
                        htmlType='submit'>
                  Submit
                </Button>
                &nbsp;
                <Button type='ghost' onClick={(e) => this.handleReset(e)}><Icon
                  type='reload'/></Button>
              </FormItem>

            </Form>
          </div>
        </Spin>
      </div>
    )
  }
}

Index = Form.create()(Index)
export default Index
